<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>流程定义管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Access-Control-Allow-Origin" content="*">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <link rel="icon" href="/favicon.ico">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/css/public.css" media="all"/>
    <!-- 确保dtree样式正确加载 -->
    <link rel="stylesheet" href="/layui_ext/dtree/dtree.css" media="all"/>
    <link rel="stylesheet" href="/layui_ext/dtree/font/dtreefont.css" media="all"/>
</head>
<body class="childrenBody">
<!-- 数据表格开始 -->
<div>
    <table class="layui-hide" id="processDefinitionTable" lay-filter="processDefinitionTable"></table>
    <div id="processDefinitionToolBar" style="display: none;">
        <button type="button" lay-event="add" class="layui-btn layui-btn-sm"
                shiro:hasPermission="process:definition:deploy">
            <span class="layui-icon layui-icon-add-1"></span>部署流程
        </button>
    </div>

    <script type="text/html" id="processDefinitionRowBar">
        <button type="button" lay-event="edit"
                class="layui-btn layui-btn-sm custom-gradient-btn"
                shiro:hasPermission="process:definition:download">
            <span class="layui-icon layui-icon-download"></span> 下载文件
        </button>
        <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-danger"
                shiro:hasPermission="process:definition:delete">
            <span class="layui-icon layui-icon-delete"></span>删除
        </button>
    </script>
</div>
<!-- 数据表格结束 -->

<!-- 添加和修改的弹出层开始 -->
<div style="display: none;padding: 5px" id="addOrUpdateDiv">
    <form action="" method="post" class="layui-form layui-form-pane" id="dataFrm" lay-filter="dataFrm">
        <div class="layui-form-item">
            <label class="layui-form-label">流程分类</label>
            <div class="layui-input-block">
                <input type="hidden" name="categoryId" id="categoryId" lay-verify="required">
                <ul id="categoryTree" class="dtree" data-id="0"></ul>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">流程文件</label>
            <div class="layui-input-block">
                <input type="file" name="file" id="uploadFile" style="display: none"> <!-- 隐藏原生文件输入 -->
                <button type="button" class="layui-btn" id="uploadBtn" >
                    <span class="layui-icon layui-icon-upload"></span>上传BPMN文件
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: center;">
                <button type="button" class="layui-btn" lay-submit lay-filter="doSubmit" id="doSubmit">
                    <span class="layui-icon layui-icon-add-1"></span>部署
                </button>
                <button type="reset" class="layui-btn layui-btn-warm">
                    <span class="layui-icon layui-icon-refresh-1"></span>重置
                </button>
            </div>
        </div>
    </form>
</div>
<!-- 添加和修改的弹出层结束 -->

<script type="text/javascript" src="/layui/layui.js"></script>
<script type="text/javascript" th:inline="none">
    layui.extend({
        dtree: '/layui_ext/dtree/dtree'
    }).use(['jquery', 'form', 'table', 'layer', 'dtree', 'upload'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var dtree = layui.dtree;
        var upload = layui.upload;


        // 表格初始化
        var tableIns = table.render({
            elem: '#processDefinitionTable',
            url: '/definition/list',
            toolbar: '#processDefinitionToolBar',
            where: {categoryId: 0},
            method: "GET",
            title: '流程定义列表',
            height: 'full-35',
            page: true,
            cols: [[
                {field: 'category', title: '流程分类', align: 'center'},
                {field: 'id', title: '流程定义ID', align: 'center'},
                {field: 'key', title: '流程定义KEY', align: 'center'},
                {
                    field: 'name', title: '流程定义名称', align: 'center', templet: function (d) {
                        return d.name || '未命名';
                    }
                },
                {field: 'version', title: '版本号', align: 'center'},
                {fixed: 'right', title: '操作', toolbar: '#processDefinitionRowBar', align: 'center', width: 240}
            ]]
        });


        // 分类树实例
        var categoryTreeInstance = null;


        // 初始化分类树（新增DOM检测）
        categoryTreeInstance = dtree.renderSelect({
            elem: "#categoryTree",
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            method: "GET",
            response: {message: "msg", statusCode: 0},
            url: "/category/tree",
        });


        // 分类树选中事件（确保赋值）
        dtree.on("node(categoryTree)", function (obj) {
            $("#categoryId").val(obj.param.nodeId);
            form.render();
        });

        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['700px', '500px'],
                title: '部署流程',
                success: function () {
                    $("#dataFrm")[0].reset();
                    $("#categoryId").val("");
                    $("#uploadFile").val("");
                    dtree.selectVal("categoryTree", "0");  // 清空树形选择
                    form.render();  // 刷新表单状态
                    url = "/definition/deploy";

                    // 异步重新加载树形数据
                    setTimeout(function () {
                        if (categoryTreeInstance && categoryTreeInstance.config) {
                            dtree.reload(categoryTreeInstance.config.elem, {});
                        }
                    }, 100);
                }
            });
        }

        // 文件上传配置
        upload.render({
            elem: '#uploadFile',
            auto: false,  // 禁止选择文件后自动上传
            accept: 'file',
            exts: 'bpmn',
        });

        $('#uploadBtn').click(function () {
            $('#uploadFile').click(); // 触发隐藏的文件输入框
        });

        // 新增：打开编辑弹层的函数
        function openLayer(title, data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['700px', '500px'],
                title: title, // 动态设置标题
                success: function () {
                    // 填充表单数据
                    form.val("dataFrm", {
                        "categoryId": data.categoryId || ""
                    });

                    // 设置分类树选中项
                    if (data.categoryId) {
                        dtree.selectVal("categoryTree", data.categoryId.toString());
                    }


                    // 显示隐藏的ID字段（如果存在）
                    $('input[name="id"]').val(data.id).parent().show();
                }
            });
        }

        // 监听文件选择事件（确保每次选择后更新状态）
        document.getElementById('uploadFile').addEventListener('change', function (e) {
            if (this.files && this.files[0]) {
                $("#fileName").html(
                    '<i class="layui-icon layui-icon-ok" style="color:#5FB878"></i> ' + this.files[0].name
                );
            } else {
                $("#fileName").html("未选择文件");
            }
        });
        window.reloadTable = function (categoryId) {
            tableIns.reload({
                where: {categoryId: categoryId},
                page: {curr: 1}
            });
        };

        // 统一处理Ajax错误
        function handleAjaxError(jqXHR) {
            let msg = "请求失败: ";
            if (jqXHR.responseJSON && jqXHR.responseJSON.msg) {
                msg += jqXHR.responseJSON.msg;
            } else {
                msg += jqXHR.statusText;
            }
            layer.msg(msg, {icon: 2});
        }

        // 事件监听
        table.on("toolbar(processDefinitionTable)", function (obj) {
            if (obj.event === 'add') openAddLayer();
        });

        table.on("tool(processDefinitionTable)", function (obj) {
            const handlers = {
                'delete': () => deleteDefinition(obj.data),
                'download': () => downloadDefinition(obj.data),
            };
            handlers[obj.event]?.();
        });

        form.on("submit(doSubmit)", function (data) {
            console.log(data);

            var fileInput = document.getElementById('uploadFile');
            console.log(fileInput);

            var categoryId = $("#categoryId").val();

            // 检查文件是否存在
            if (!fileInput.files || fileInput.files.length === 0) {
                layer.msg("请选择BPMN文件", {icon: 2});
                return false;
            }
            // 检查文件格式
            var fileName = fileInput.files[0].name;
            if (!fileName.toLowerCase().endsWith(".bpmn")) {
                layer.msg("仅支持 .bpmn 格式文件", {icon: 2});
                return false;
            }

            if (!categoryId) {
                layer.msg("请选择流程分类", {icon: 2});
                return false;
            }

            //======= 构建FormData =======//
            var formData = new FormData();
            formData.append("file", fileInput.files[0]);

            // 添加公共参数
            formData.append("categoryId", categoryId);

            //======= 提交按钮状态 =======//
            var $doSubmit = $("#doSubmit");
            $doSubmit.prop("disabled", true).html('<span class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></span> 提交中...');

            //======= 发送请求 =======//
            var requestUrl = "/definition/deploy";
            $.ajax({
                url: requestUrl,
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function (res) {
                    if (res.code === 200) {
                        layer.close(mainIndex);
                        tableIns.reload();
                    } else {
                        layer.msg(res.msg || "操作失败", {icon: 2});
                    }
                },
                error: function (xhr) {
                    handleAjaxError(xhr);
                },
                complete: function () {

                }
            });
            return false;
        });

        // 操作函数（统一错误处理）
        function deleteDefinition(data) {
            layer.confirm(`确认删除【${data.name}】流程定义？`, {icon: 3}, function (index) {
                $.post(`/definition/delete/${data.id}`, {id: data.id})
                    .done(res => tableIns.reload())
                    .fail(handleAjaxError)
                    .always(() => layer.close(index));
            });
        }

        function downloadDefinition(data) {
            $.get(`/definition/${data.id}/data`).done().fail(handleAjaxError).always(() => layer.close(index));
        }

    });
</script>
</body>
</html>